package indi.mozping.MySerilizable;


import org.apache.kafka.common.serialization.Serializer;

import java.nio.ByteBuffer;
import java.util.Map;

/**
 * @Classname ItemSerilializer
 * @Description TODO
 * @Date 2019/7/20 12:15
 */
public class ItemSerilializer implements Serializer<Item> {
    @Override
    public void configure(Map configs, boolean isKey) {

    }

    @Override
    public byte[] serialize(String topic, Item data) {
        if (data == null) {
            return null;
        }
        byte[] name, detail;
        try {


            if (data.getName() != null) {
                name = data.getName().getBytes();
            } else {
                name = new byte[0];
            }

            if (data.getDetail() != null) {
                detail = data.getDetail().getBytes();
            } else {
                detail = new byte[0];
            }
            //1.分配内存
            ByteBuffer byteBuffer = ByteBuffer.allocate(4 + 4 + name.length + detail.length);
            //2.设置写入字节数
            byteBuffer.putInt(name.length);
            //3.写入内容
            byteBuffer.put(name);
            byteBuffer.putInt(detail.length);
            byteBuffer.put(detail);
            return byteBuffer.array();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    @Override
    public void close() {

    }
}